using System;
using System.Runtime.Serialization;
using System.Text;

namespace MiniStock.Entities.Common.Query
{
    [DataContract]
    public class FilterElement
    {
        [DataMember]
        public string FieldName { get; set; }
        [DataMember]
        public QueryOperator Operator { get; set; }
        [DataMember]
        public string FieldValue { get; set; }

        public static FilterElement Equals(string field, string value)
        {
            return new FilterElement {FieldName = field, Operator = QueryOperator.Equals, FieldValue = value};
        }

        public string ToSql()
        {
            var sb = new StringBuilder();
            sb.Append(FieldName);
            bool isUnary = false;
            switch(Operator)
            {
                case QueryOperator.Equals:
                    sb.Append(" = ");
                    break;
                case QueryOperator.NotEquals:
                    sb.Append(" != ");
                    break;
                case QueryOperator.LessThan:
                    sb.Append(" < ");
                    break;
                case QueryOperator.LessEquals:
                    sb.Append(" <= ");
                    break;
                case QueryOperator.GreaterThan:
                    sb.Append(" > ");
                    break;
                case QueryOperator.GreatEquals:
                    sb.Append(" >= ");
                    break;
                case QueryOperator.In:
                    sb.Append(" IN ");
                    break;
                case QueryOperator.Between:
                    sb.Append(" BETWEEN ");
                    break;
                case QueryOperator.Like:
                    sb.Append(" LIKE ");
                    break;
                case QueryOperator.IsNull:
                    sb.Append(" IS NULL");
                    isUnary = true;
                    break;
                case QueryOperator.IsNotNull:
                    sb.Append(" IS NULL");
                    isUnary = true;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            if(!isUnary) sb.Append(FieldValue);
            return sb.ToString();
        }
    }
}